package controllers;

import com.ning.http.util.Base64;
import models.data.*;
import models.domain.*;
import models.general.HelperFunctions;
import models.general.vAfangarBaekur;
import models.general.vNemandiAfangarOnn;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.mvc.Security;

import views.html.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Kristborg
 * Date: 26.2.2013
 * Time: 12:30
 * To change this template use File | Settings | File Templates.
 */
@Security.Authenticated(Secured.class)
public class StudentController extends Controller {
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");  //To format the dates
    final static Form<Athugasemdir> athugasemdForm = form(Athugasemdir.class);
    private final static String userId =session().get("notandiId");  //The userID
    private final static int intNotandi = Integer.parseInt(userId); //the userID converted to int number
    private final static List<vNemandiAfangarOnn> afangar = vNemandiAfangarOnn.getCoursesClasses(intNotandi);//All the courses a student is taking
    private final static List<vAfangarBaekur> courseBooks = vAfangarBaekur.getAllBaekurByList(afangar); //All the books taught in the courses the student is taking

    //Function called to show the studentDashboard
    public static Result studentDashboard() {
        String nafn = session().get("nafn");
        if(isTeacher(session().get("notandiId"))) {
            return redirect(routes.TeacherController.teacherDashboard());
        }
        boolean isProjectreturned = false;

        //foreach course
        List<verkefninemenda>  verkNem = verkefninemenda.findAllById(userId);
        List<Project> projects = new ArrayList<Project>();
        Date today = new Date();

        //foreach assignment registered to this student
        for(verkefninemenda single : verkNem){
            verkefnihops vhops = verkefnihops.findProjectByVerkefniHopsID(single.getVerkefnihops_id());
            Double grade = 20.0;
            Date lokadagsetning = vhops.lokadagsetning;
            Date upphafsdagsetning = vhops.upphafsdagsetning;
            //if the assignment is open and hasn't closed (the assignment handInDate has not arrived yet and the beginDate has arrived)
            if(today.before(lokadagsetning) && today.after(upphafsdagsetning)){
                String loka = simpleDateFormat.format(lokadagsetning);
                String upphafs = simpleDateFormat.format(upphafsdagsetning);
                Afangar afangi = Afangar.getAfangi(vhops.afangi_id); //used to be able to show the name of the course, not just the id
                Verkefni verkefni = Verkefni.findProjectByVerkefniID(single.verkefni_id); //need this to get the name of the assignment etc.

                int returned = verkefninemenda.hasStudentTurnedInProject(verkefni.verkefni_id, intNotandi);
                if (returned == 1)
                    isProjectreturned = true;
                else
                    isProjectreturned = false;

                if(verkefni.tegund.equals("verkefni")){
                    projects.add(new Project(verkefni.heiti,grade,verkefni.vaegi,afangi.namsgrein_afanganr,isProjectreturned,upphafs,loka,"project",verkefni.verkefni_id, lokadagsetning));
                }
                else if(verkefni.tegund.equals("prof")){
                    projects.add(new Project(verkefni.heiti,grade,verkefni.vaegi,afangi.namsgrein_afanganr,isProjectreturned,upphafs,loka,"test",verkefni.verkefni_id,lokadagsetning));
                }
            }
        }
        List<TimetableHomework> monday = new ArrayList<TimetableHomework>();
        List<TimetableHomework> tuesday = new ArrayList<TimetableHomework>();
        List<TimetableHomework> wednesday = new ArrayList<TimetableHomework>();
        List<TimetableHomework> thursday = new ArrayList<TimetableHomework>();
        List<TimetableHomework> friday = new ArrayList<TimetableHomework>();

        List<List<Stundatoflur_NK>> stundatafla = Stundatoflur_NK.getStudentStundatafla(afangar);  //List that has a seperate list for the course schedule each day
        List<List<Heimavinna>> heimavinna = Heimavinna.getStudentHomeworkWeek(afangar);  //List that has a seperate list for the homework each day
        List<TimetableHomework> All = TimetableHomework.makeTimetableHomework(stundatafla, heimavinna);

        for (TimetableHomework dagur : All) {
            if(dagur.getDagur().equals("manudagur")){
                monday.add(dagur);
            }
            if(dagur.getDagur().equals("thridjudagur")){
                tuesday.add(dagur);
            }
            if(dagur.getDagur().equals("midvikudagur")){
                wednesday.add(dagur);
            }
            if(dagur.getDagur().equals("fimmtudagur")){
                thursday.add(dagur);
            }
            if(dagur.getDagur().equals("fostudagur")){
                friday.add(dagur);
            }

        }

        List<Tilkynning> tilkynningList = Tilkynning.getStudentTopFiveAnnouncements(afangar); //get top announcements associated with this user
        List<Announcements> announcements = Announcements.createAnnouncementList(tilkynningList);
        List<Athugasemdir> athugasemdir = Athugasemdir.getNewerComments(userId);//get the newest comments to display under new comments
        List<Comments> newerComments = Comments.createCommentList(athugasemdir);
        projects = CommonController.sortProjectsByDate(projects);
        List<Project> displayProjects = new ArrayList<Project>();
        if(projects.size() > 5){
            for(int i = 0; i < 5 ; i++){
                displayProjects.add(projects.get(i));
            }
        }
        else{
            for(int i = 0; i< projects.size(); i++){
                displayProjects.add(projects.get(i));
            }
        }

        return ok(StudentDashboard.render(displayProjects, afangar, announcements,newerComments,monday, tuesday, wednesday, thursday, friday, nafn));
    }

    //Checks if the user has the right to watch this view
    public static boolean isTeacher(String userId){
        if(Notendur.checkIfStudent(userId)){
            return false;
        }
        else
            return true;
    }

    //Get all the comments that the student has commented on
    public static Result allStudentDiscussions() {
        List<Athugasemdir> athugasemdir = Athugasemdir.getAllComments(userId);
        List<Comments> comments = Comments.createCommentList(athugasemdir);
        return ok(AllStudentDiscussions.render(comments));

    }

    //Function called to show all assignments registered to this user, both those that are still open and those that are closed
    public static Result assignments() {
        if(isTeacher(session().get("notandiId"))) {
            return redirect(routes.TeacherController.teacherDashboard());
        }

        String userId = session().get("notandiId");
        List<Project> openProjects = new ArrayList<Project>();
        List<Project> closedProjects = new ArrayList<Project>();
        Double grade = 20.0;
        String loka = "";
        String begin = "";
        Date lokadagsetning = new Date();
        Date upphafsdagsetning = new Date();
        Date today = new Date();
        boolean isProjectreturned = false;

        List<verkefninemenda> nemenda = verkefninemenda.findAllByUserId(userId);  //get all assignments registered to this user
        for(verkefninemenda single : nemenda) {
            verkefnihops vhops = verkefnihops.findProjectByVerkefniHopsID(single.getVerkefnihops_id());
            lokadagsetning = vhops.lokadagsetning;
            upphafsdagsetning = vhops.upphafsdagsetning;
            Verkefni verkefni = Verkefni.findProjectByVerkefniID(single.getVerkefni_id());
            loka = simpleDateFormat.format(lokadagsetning);
            begin = simpleDateFormat.format(upphafsdagsetning);
            grade = verkefninemenda.getGrade(single.verkefni_id, userId); //get the grade the user got for the assignment
            int returned = verkefninemenda.hasStudentTurnedInProject(single.verkefni_id, Integer.parseInt(userId));
            Afangar afangi = Afangar.getAfangi(verkefni.getAfangi_id());
            if (returned == 1){
                isProjectreturned = true;
            }
            else{
                isProjectreturned = false;
            }

            if(today.before(lokadagsetning) && today.after(upphafsdagsetning)){
                if(verkefni.getTegund().equals("verkefni")){
                    openProjects.add(new Project(verkefni.heiti,grade,verkefni.vaegi,afangi.namsgrein_afanganr,isProjectreturned,begin, loka,"project",verkefni.verkefni_id, lokadagsetning));
                }
            }
            else {
                if(verkefni.getTegund().equals("verkefni") && today.after(upphafsdagsetning)){
                    closedProjects.add(new Project(verkefni.heiti,grade,verkefni.vaegi,afangi.namsgrein_afanganr,isProjectreturned,begin, loka,"project",verkefni.verkefni_id, lokadagsetning));
                }

            }

        }
        openProjects = CommonController.sortProjectsByDate(openProjects);
        closedProjects = CommonController.sortProjectsByDate(closedProjects);
        return ok(assignments.render(openProjects, closedProjects));
    }

    //Function called to show all open assignments registered to this user
    public static Result studentOpenAssignments() {
        if(isTeacher(session().get("notandiId"))) {
            return redirect(routes.TeacherController.teacherDashboard());
        }
        String userId = session().get("notandiId");
        List<Project> openProjects = new ArrayList<Project>();
        Double grade = 20.0;
        String loka = "";
        String begin = "";
        Date lokadagsetning = new Date();
        Date upphafsdagsetning = new Date();
        Date today = new Date();
        boolean isProjectreturned = false;

        List<verkefninemenda> nemenda = verkefninemenda.findAllByUserId(userId);  //get all assignments registered to this user
        for(verkefninemenda single : nemenda) {
            verkefnihops vhops = verkefnihops.findProjectByVerkefniHopsID(single.getVerkefnihops_id());
            lokadagsetning = vhops.lokadagsetning;
            upphafsdagsetning = vhops.upphafsdagsetning;
            Verkefni verkefni = Verkefni.findProjectByVerkefniID(single.getVerkefni_id());
            loka = simpleDateFormat.format(lokadagsetning);
            begin = simpleDateFormat.format(upphafsdagsetning);
            grade = verkefninemenda.getGrade(single.verkefni_id, userId); //get the grade the user got for the assignment
            int returned = verkefninemenda.hasStudentTurnedInProject(single.verkefni_id, Integer.parseInt(userId));
            Afangar afangi = Afangar.getAfangi(verkefni.getAfangi_id());
            if (returned == 1){
                isProjectreturned = true;
            }
            else{
                isProjectreturned = false;
            }

            if(today.before(lokadagsetning)){
                openProjects.add(new Project(verkefni.heiti,grade,verkefni.vaegi,afangi.namsgrein_afanganr,isProjectreturned,begin, loka,"project",verkefni.verkefni_id, lokadagsetning));
            }
        }
        openProjects = CommonController.sortProjectsByDate(openProjects);
        return ok(StudentOpenAssignments.render(openProjects));
    }


    //Function called to show all exams registered to this user, both those that are still open and those that are closed
    public static Result exams() {
        if(isTeacher(session().get("notandiId"))) {
            return redirect(routes.TeacherController.teacherDashboard());
        }
        String userId = session().get("notandiId");
        List<Project> openExams = new ArrayList<Project>();
        List<Project> closedExams = new ArrayList<Project>();
        double grade = 20.0;
        String loka = "";
        String begin = "";
        Date lokadagsetning = new Date();
        Date upphafsdagsetning = new Date();
        Date today = new Date();
        boolean isProjectreturned = false;

        List<verkefninemenda> nemenda = verkefninemenda.findAllByUserId(userId);  //get all assignments registered to this user
        for(verkefninemenda single : nemenda) {
            verkefnihops vhops = verkefnihops.findProjectByVerkefniHopsID(single.getVerkefnihops_id());
            lokadagsetning = vhops.lokadagsetning;
            upphafsdagsetning = vhops.upphafsdagsetning;
            Verkefni verkefni = Verkefni.findProjectByVerkefniID(single.getVerkefni_id());
            loka = simpleDateFormat.format(lokadagsetning);
            begin = simpleDateFormat.format(upphafsdagsetning);
            grade = verkefninemenda.getGrade(single.verkefni_id, userId); //get the grade the user got for the assignment
            int returned = verkefninemenda.hasStudentTurnedInProject(single.verkefni_id, Integer.parseInt(userId));
            Afangar afangi = Afangar.getAfangi(verkefni.getAfangi_id());

            if (returned == 1){
                isProjectreturned = true;
            }
            else{
                isProjectreturned = false;
            }

            if(today.before(lokadagsetning) && today.after(upphafsdagsetning)){
                if(verkefni.getTegund().equals("prof")){
                    openExams.add(new Project(verkefni.heiti,grade,verkefni.vaegi,afangi.namsgrein_afanganr,isProjectreturned,begin, loka,"test",verkefni.verkefni_id, lokadagsetning));
                }
            }
            else {
                if(verkefni.getTegund().equals("prof") && today.after(upphafsdagsetning)){
                    closedExams.add(new Project(verkefni.heiti,grade,verkefni.vaegi,afangi.namsgrein_afanganr,isProjectreturned,begin, loka,"test",verkefni.verkefni_id,lokadagsetning));
                }
            }
        }
        openExams = CommonController.sortProjectsByDate(openExams);
        closedExams = CommonController.sortProjectsByDate(closedExams);
        return ok(exams.render(openExams, closedExams));
    }

    //used in studentOneProject to check if the grade is between the pillars on the chart shown for the total number of grades for assignment/exam
    public static boolean isBetween(double x, double lower, double upper){
        return lower <=x && x<upper;
    }

    //helper function for studentOneProject to present the graph for all grades for a particular project/exam
    public static List<Graph> addToGraphData(List<Graph> graphData, verkefnihops vhops, int verkefni_id, String userId){
        Date today = new Date();
        double einkunn = 0.0;
        boolean skilafresturLidinn = false;
        Boolean einkunnBirt = false;


        if(today.before(vhops.lokadagsetning))
        {
            einkunn = 20.0; //Try to stop null exceptions.
            skilafresturLidinn = false;
        }
        else{
            skilafresturLidinn = true;
            for(double i = 0; i <= 10 ; i+=0.5){

                graphData.add(new Graph(i,0,false)); //We create the x-axis which is 0, 0.5, 1, 1.5.........10 and the y is 0
            }

            List<verkefninemenda> verkefninemendas = verkefninemenda.findByVerkefniID(verkefni_id);  //We get the projects all the students handed in for this project.
            for(verkefninemenda vnem : verkefninemendas){
                //If the grade hasn't been entered we put einkunn =20.0 so we don't get null exceptions.
                Double tempEinkunn = vnem.einkunn;//Otherwise we get the grade for each student
                einkunnBirt = true;
                //We check in what space the grade should be in (like if grade = 8,3 then it should be between 8 and 8.5) and increase the y-axis.
                for(double i = 0; i < 9.5 ; i+= 0.5){
                    if(isBetween(tempEinkunn,i, (i+0.5))){
                        if(isCloser(tempEinkunn,i,(i+0.5)) == i){
                            if(vnem.nemandi_id.equals(userId)){
                                graphData.get((int) (i*2)).setYou(true);
                            }
                            graphData.get((int)(i*2)).incrementY();
                        }
                        else{
                            if(vnem.getNemandi_id().equals(userId)){
                                graphData.get((int) ((i+0.5)*2)).setYou(true);
                            }
                            graphData.get((int)((i+0.5)*2)).incrementY();
                        }
                    }
                }
            }
        }
        return graphData;
    }

    public static Result studentOneProject(int verkefni_id){
        if(isTeacher(session().get("notandiId"))) {
            return redirect(routes.TeacherController.teacherDashboard());
        }
        //all variables
        //Information about the student
        String userId = session().get("notandiId");
        String loggedInStudent = session().get("nafn");
        String loggedInKt = session().get("kennitala");

        Verkefni verk = Verkefni.findProjectByVerkefniID(verkefni_id); //Details about this project like the name etc
        vNemandiAfangarOnn afangar = vNemandiAfangarOnn.findByStudentAndAfangiID(Integer.parseInt(userId), Integer.parseInt(verk.getAfangi_id()));
        verkefnihops vhops = verkefnihops.findProjectByVerkefniIDHopsID(verkefni_id, afangar.getHopur_id());//Details about the project for this group like when to turn it in etc
        String heiti = verk.heiti; //Name of the project
        Date upphafsdagsetning = vhops.upphafsdagsetning;
        Date lokadagsetning = vhops.lokadagsetning;
        int hopurId = vhops.hopur_id;
        int hopskil = vhops.hopskil;

        //Have to convert the date to a string format so it is easier to print it on the screen
        String upphafs = simpleDateFormat.format(upphafsdagsetning);
        String loka = simpleDateFormat.format(lokadagsetning);
        Double vaegi = verk.vaegi;
        String tegund = verk.tegund;
        Double einkunn = 20.0;
        String athugasemd = vhops.getAthugasemd();
        Boolean isAttachment = false;

        List<Graph> graphData = new ArrayList<Graph>();

        Date today = new Date();
        Boolean einkunnBirt = false;
        Boolean skilafresturLidinn = false;

        //graphData = addToGraphData(graphData, vhops, verkefni_id,userId);
        if(today.before(lokadagsetning))
        {
            einkunn = 20.0; //Try to stop null exceptions.
            skilafresturLidinn = false;
        }
        else{
            skilafresturLidinn = true;
            einkunnBirt = true;
            graphData = addToGraphData(graphData, vhops, verkefni_id,userId);
        }


        //all questions from the assignment fetched to be able to print them to the screen
        List<Verkefnaspurningar> verkefnaspurningars = Verkefnaspurningar.getByVerkefniID(verkefni_id);  //All the questions for the assignment
        //get nemandi_id to check if the student has returned project or if not, to create a record in verkefniskil table
        verkefninemenda vnem = verkefninemenda.findByUserAndVerkefniID(verkefni_id, userId);

        //check to see if student has received a grade for the assignment and if so, put einkunn as that value
        //if einkunn = 20, then the student has not received a grade
        einkunn = vnem.einkunn;

        verkefnaskil verkefnaskilNemenda;
        int verkefnaskil_id = 0;
        String athugasemdNemenda = null;

        //Check if the student has already handed in the assignment.
        if((verkefnaskil.findByVerkefniNemandiID(userId, vnem.verkefninemanda_id)) == null){
            verkefnaskilNemenda = null;
        }
        else{
            verkefnaskilNemenda = verkefnaskil.findByVerkefniNemandiID(userId, vnem.verkefninemanda_id) ;
            athugasemdNemenda = verkefnaskilNemenda.athugasemd;
            verkefnaskil_id = verkefnaskilNemenda.verkefnaskil_id;
        }


        List<Integer> spurningarID = new ArrayList<Integer>(); //add together all the ids for the questions so we can get all the correct answers
        List<SpurningarModel> spurningars = new ArrayList<SpurningarModel>(); //The questions we are going to print

        List<Vidhengitafla> vidhengiFraKennara = new ArrayList<Vidhengitafla>();

        //Go through all the questions in the project to see how we would present them
        for(Verkefnaspurningar vspurn : verkefnaspurningars){
            Spurningar spurn = Spurningar.getByID(vspurn.spurningar_id); //Get each question in the assignment
            if(Vidhengitafla.doesVidhengiExist(spurn.getSpurningar_id()) == true && spurn.tegund.equals("vidhengi")){
                Vidhengitafla vidhengiKenn = Vidhengitafla.getVidhengiAll(spurn.getSpurningar_id());
                vidhengiFraKennara.add(new Vidhengitafla(vidhengiKenn.getSpurning_id(),vidhengiKenn.getNafn(),vidhengiKenn.getVidhengiVariable(),vidhengiKenn.getKennari_id_buidtil(),vidhengiKenn.getDagur_buidtil(),vidhengiKenn.getContenttype()));
            }
            if(spurn.tegund.equals("texti")){
                if(verkefnaskilNemenda != null){  //If the student has already answered this question then we want to print that on the screen.
                    List<Verkefnaskilspurningar> verkefnaskilspurningar = Verkefnaskilspurningar.getSvorWithVerkefniID(verkefnaskilNemenda.verkefnaskil_id,spurn.getSpurningar_id());
                    spurningars.add(new SpurningarModel(spurn.getSpurningar_id(),spurn.tegund,spurn.texti,1,verkefnaskilspurningar.get(0).svar, vspurn.vaegi));

                }
                else{
                    spurningars.add(new SpurningarModel(spurn.getSpurningar_id(),spurn.tegund,spurn.texti,1, vspurn.vaegi));
                }
            }
            if(spurn.tegund.equals("eydufylling")){
                List<String> svor = null;

                if(verkefnaskilNemenda != null){
                    List<Svor> eydufylling = Svor.getSvorBySpurningID(spurn.getSpurningar_id());
                    List<String> strings = HelperFunctions.splitEydufylling(eydufylling.get(0).getTexti());
                    List<Verkefnaskilspurningar> vsvor = Verkefnaskilspurningar.getSvorWithVerkefniID(verkefnaskilNemenda.verkefnaskil_id,spurn.getSpurningar_id());
                    svor = new ArrayList<String>();
                    for(Verkefnaskilspurningar verkefnasvor : vsvor){
                        svor.add(verkefnasvor.getSvar());
                    }
                    spurningars.add(new SpurningarModel(spurn.getSpurningar_id(),spurn.tegund,spurn.getTexti(),strings, (strings.size()-1),svor,vspurn.vaegi));
                }
                else{
                    List<Svor> eydufylling = Svor.getSvorBySpurningID(spurn.getSpurningar_id());
                    List<String> strings = HelperFunctions.splitEydufylling(eydufylling.get(0).getTexti());
                    spurningars.add(new SpurningarModel(spurn.getSpurningar_id(),spurn.tegund,spurn.getTexti(),strings, (strings.size()-1),svor,vspurn.vaegi));
                }
            }
            if(spurn.tegund.equals("mynd")){
                if(verkefnaskilNemenda != null){
                    byte[] vidhengi =  Vidhengitafla.getVidhengi(spurn.getSpurningar_id());
                    String encodedImage = Base64.encode(vidhengi); //To display the picture
                    List<Verkefnaskilspurningar> verkefnaskilspurningar = Verkefnaskilspurningar.getSvorWithVerkefniID(verkefnaskilNemenda.verkefnaskil_id, spurn.getSpurningar_id());
                    spurningars.add(new SpurningarModel(spurn.getSpurningar_id(),spurn.tegund,spurn.texti,encodedImage,1,verkefnaskilspurningar.get(0).svar,vspurn.vaegi));

                }
                else{
                    byte[] vidhengi =  Vidhengitafla.getVidhengi(spurn.getSpurningar_id());
                    String encodedImage = Base64.encode(vidhengi);
                    spurningars.add(new SpurningarModel(spurn.getSpurningar_id(),spurn.tegund,spurn.texti,encodedImage,1,vspurn.vaegi));
                }
            }
            if(spurn.tegund.equals("krossar")){
                List<Svor> svor = Svor.getSvorBySpurningID(spurn.getSpurningar_id());
                List<String> krossaSvor = new ArrayList<String>();
                List<Integer> krossaSvorID = new ArrayList<Integer>();
                Integer rettSvar = 0;
                Integer svarNemanda= 0;
                spurningarID.add(vspurn.spurningar_id);
                for(Svor s: svor){
                    krossaSvor.add(s.getTexti());  //The answers to one question
                    krossaSvorID.add(s.getSvar_id());  //Their ids
                    if(s.getRettsvar() == 1){
                        rettSvar = s.getSvar_id();
                    }
                }

                if(verkefnaskilNemenda != null){
                    List<Verkefnaskilspurningar> verkefnaskilspurningar = Verkefnaskilspurningar.getSvorWithVerkefniID(verkefnaskilNemenda.verkefnaskil_id,spurn.getSpurningar_id());
                    if(verkefnaskilspurningar.size() > 0){
                        svarNemanda = Integer.parseInt(verkefnaskilspurningar.get(0).getSvar());
                    }
                    spurningars.add(new SpurningarModel(spurn.getSpurningar_id(),spurn.tegund,spurn.texti,krossaSvor,krossaSvorID,svarNemanda,1,vspurn.vaegi, rettSvar));

                }
                else{
                    spurningars.add(new SpurningarModel(spurn.getSpurningar_id(),spurn.tegund, spurn.texti,krossaSvor,krossaSvorID,1,vspurn.vaegi, rettSvar));
                }
            }
            if(spurn.tegund.equals("fjolval")){
                List<Svor> svor = Svor.getSvorBySpurningID(spurn.getSpurningar_id());
                List<String> krossaSvor = new ArrayList<String>();
                List<Integer> krossaSvorID = new ArrayList<Integer>();
                List<Integer> rettSvor = new ArrayList<Integer>();
                spurningarID.add(vspurn.spurningar_id);
                for(Svor s : svor){
                    if(s.getTexti() == null){
                        krossaSvor.add("");
                    }
                    else{
                        krossaSvor.add(s.getTexti());
                    }
                    krossaSvorID.add(s.getSvar_id());
                    if(s.getRettsvar() == 1){
                        rettSvor.add(s.getSvar_id());
                    }
                }
                List<Integer> rettSvorList = new ArrayList<Integer>();
                for(Integer svarID : krossaSvorID){
                    if(TeacherController.isCorrectAnswerFjolval(rettSvor,svarID)== true){
                        rettSvorList.add(1);
                    }
                    else{
                        rettSvorList.add(0);
                    }
                }

                //fjolvalOllSvor.add(new MultipleChoice(spurn.getSpurningar_id(),krossaSvorID)); //Want to have all the answers to each fjolvalsspurning in one list to help us make the correct answer bold.
                if(verkefnaskilNemenda != null){
                    List<Verkefnaskilspurningar> verkefnaskilspurningar = Verkefnaskilspurningar.getSvorWithVerkefniID(verkefnaskilNemenda.verkefnaskil_id,spurn.getSpurningar_id());
                    List<Integer> nemendaSvorList = new ArrayList<Integer>();
                     for(Integer svarID: krossaSvorID){
                         if(TeacherController.isStudentAnswerFjolval(verkefnaskilspurningar,svarID)== true){
                             nemendaSvorList.add(1);
                         }
                         else{
                             nemendaSvorList.add(0);
                         }
                     }

                    spurningars.add(new SpurningarModel(spurn.getSpurningar_id(),spurn.tegund,spurn.texti,krossaSvor,krossaSvorID, 1,vspurn.vaegi,rettSvorList,nemendaSvorList));
                }
                else{

                    spurningars.add(new SpurningarModel(spurn.getSpurningar_id(),spurn.tegund, spurn.texti,krossaSvor,krossaSvorID,1,vspurn.vaegi, rettSvorList));
                }
            }


        }
        List<Vidhengitaflanemendur> vidhengiNemenda = null;

        if(Vidhengitaflanemendur.getVidhengiList(verkefnaskil_id) != null){
            vidhengiNemenda = Vidhengitaflanemendur.getVidhengiList(verkefnaskil_id);
        }
        boolean isProjectReturned;

        int returned = verkefninemenda.hasStudentTurnedInProject(verkefni_id, Integer.parseInt(userId));
        if (returned == 1){
            isProjectReturned = true;
        }
        else{
            isProjectReturned = false;
        }
        //Details about the project added to be able to send it to the view
        Project project;
        if(vhops.athugasemd == null){
            project = new Project(heiti, einkunn,vaegi, upphafs,loka,verkefni_id,einkunnBirt,
                    verkefninemenda.findByUserAndVerkefniID(verkefni_id, userId).verkefninemanda_id, isProjectReturned, tegund, null);
        }
        else{
            project = new Project(heiti, einkunn,vaegi, upphafs,loka,verkefni_id,einkunnBirt,
                    verkefninemenda.findByUserAndVerkefniID(verkefni_id, userId).verkefninemanda_id, isProjectReturned, tegund, vhops.getAthugasemd());
        }

        List<vNemandiAfangarOnn> listOfStudentsInGroup = vNemandiAfangarOnn.findStudentsByGroup(hopurId);
        if(vidhengiFraKennara == null){
            vidhengiFraKennara = null;
        }
        return ok(studentOneProject.render(athugasemdForm,graphData,project, fillCommentList(verkefni_id),spurningars,
                loggedInStudent, loggedInKt, listOfStudentsInGroup, hopskil, userId, skilafresturLidinn, athugasemdNemenda, vidhengiNemenda,vidhengiFraKennara, hopurId));
    }

    //Checks  if an id is in a list of integers
    public static boolean isCorrectAnswerMultipleChoice(List<Integer> ids, int id){
        for(Integer i : ids){
            if(i == id){
                return true;
            }
        }
        return false;
    }

    //get all the comments for a particular project
    public static List<Comments> fillCommentList(Integer verkefni_id){
        List<Athugasemdir> athugasemdir = Athugasemdir.find.where().eq("verkefni_id", verkefni_id).findList();
        List<Comments> commentList = Comments.createCommentList(athugasemdir);
        return commentList;
    }

    //Checks if the question with spurningar_id is the list vskil
    //used in submit assignment
    public static boolean isPartof(List<Verkefnaskilspurningar> vskil, int spurningar_id){
        for(Verkefnaskilspurningar v : vskil){
            if(v.getSpurning_id() == spurningar_id){
                return true;
            }
        }
        return false;
    }

    //Checks if the answer "svar" the correct answer for the question stored in vskil
    public static boolean isCorrectAnswear(List<Verkefnaskilspurningar> vskil, int svar){
        for(Verkefnaskilspurningar v : vskil){
            if(Integer.parseInt(v.getSvar()) == svar){
                return true;
            }
        }
        return false;
    }

    //Function called when an assignment is submitted
    public static Result submitAssignment(int verkefniNemenda_Id, int verkefni_id){
        Http.MultipartFormData body = request().body().asMultipartFormData();
        String[] notandiId = body.asFormUrlEncoded().get("notandiId");

        //Submits the answers for every student that submitted (if it is allowed to submit for more than one student).
        for(int i = 0; i < notandiId.length; i++)
        {
            String notandId = notandiId[i];
            if(!(notandId.equals("null")) ){
                String[] athugasemd = body.asFormUrlEncoded().get("athugasemd");
                int verkefnaskil_id ;
                //Creates an instance in the verkefniskil table.
                if(verkefnaskil.findByVerkefniNemandiID(notandId, verkefniNemenda_Id) != null){//There is already an instance in the table so we update rather than create
                    //Athugasemd can be empty so we have a special case.
                    if(athugasemd.length == 0){
                        verkefnaskil_id = verkefnaskil.updateWithoutAthugasemdAndFile(verkefniNemenda_Id, notandId);
                    }
                    else{
                        verkefnaskil_id = verkefnaskil.updateWithoutFile(verkefniNemenda_Id, notandId, athugasemd[0]);
                    }
                }
                else{//Create new instance
                    if(athugasemd.length == 0){
                        verkefnaskil vskil = verkefnaskil.createWithoutAthugasemd(verkefniNemenda_Id, notandId);
                        verkefnaskil_id = vskil.verkefnaskil_id;
                    }
                    else{
                        verkefnaskil vskil = verkefnaskil.create(verkefniNemenda_Id, notandId, athugasemd[0]);
                        verkefnaskil_id = vskil.verkefnaskil_id;
                    }
                }

                Http.MultipartFormData.FilePart vidhengi = null;
                if(body.getFile("vidhengi") != null){
                    vidhengi = body.getFile("vidhengi");         //Get the vidhengi and create an instance in the Vidhengitaflanemendur table.
                    List<String> nafnKt = vNemandiAfangarOnn.findByStudentID(intNotandi);
                    String[] nafn = nafnKt.get(0).split(" ");
                    String vidhengiNafn = nafn[0] + "_" + nafnKt.get(1) + "_" + vidhengi.getFilename();
                    Vidhengitaflanemendur.create(verkefnaskil_id,vidhengiNafn,vidhengi.getFile(),notandId, verkefninemenda.findbyVerkefniNemendaID(verkefniNemenda_Id).verkefnihops_id,vidhengi.getContentType());
                }

                String[] postAction = body.asFormUrlEncoded().get("spurning_id");//The question id's
                String[] questionAction = body.asFormUrlEncoded().get("svar"); //The answers
                String[] tegund = body.asFormUrlEncoded().get("tegund"); //The types of the questions
                String[] fjoldiSvaraSpurningar = body.asFormUrlEncoded().get("fjoldi_svara");//the number of answers, eydufylling has more  than one answer.


                List<String> krossar = new ArrayList<String>();
                int fsvar = 0;//Don't want to have nested loop so we have fsvar to keep track of the answers because the answers don't have to be as many as the questions.
                List<Verkefnaskilspurningar> verkefnaskilspurningar = Verkefnaskilspurningar.findByVerkefnaskilID(verkefnaskil_id);//the questions for this assignment
                if(postAction != null){
                    int fjoldiSpurninga = postAction.length; //Number of questions
                    for(int spurn = 0; spurn < fjoldiSpurninga ; spurn++){ //Go through all the questions
                        String spurningarID = postAction[spurn];
                        if(tegund[spurn].equals("texti")){
                            //String spurningarID = postAction[spurn];
                            String svar = questionAction[fsvar];
                            if(verkefnaskilspurningar != null && isPartof(verkefnaskilspurningar,Integer.parseInt(spurningarID))){ //The student has already submitted so we want to update his answer
                                Verkefnaskilspurningar.update(verkefnaskil_id, Integer.parseInt(spurningarID), svar);
                            }
                            else{
                                Verkefnaskilspurningar.create(verkefnaskil_id, Integer.parseInt(spurningarID),svar);
                            }
                            fsvar++;

                        }
                        if(tegund[spurn].equals("eydufylling")){
                            int fjoldi = fsvar + Integer.parseInt(fjoldiSvaraSpurningar[spurn]);
                            for(int j = fsvar; j <fjoldi ; j++){
                                String svar = questionAction[fsvar];
                                if(verkefnaskilspurningar != null && isPartof(verkefnaskilspurningar,Integer.parseInt(spurningarID))){//The student has already submitted so we want to update his answer
                                    List<Integer> ids = Verkefnaskilspurningar.findforEydufylling(verkefnaskil_id, Integer.parseInt(spurningarID)); //Find all the answers for eydufylling
                                    for(Integer id: ids){
                                        Verkefnaskilspurningar.updateEydufylling(id,verkefnaskil_id, Integer.parseInt(spurningarID),questionAction[fsvar]); //Then we update each of them
                                        fsvar++;
                                    }
                                    break;
                                }
                                else{
                                    Verkefnaskilspurningar.create(verkefnaskil_id, Integer.parseInt(spurningarID),svar); //Otherwise we create a new instance in verkefnaskilspurningar table which contains the
                                    //students answer.
                                }
                                fsvar++;
                            }
                        }
                        if(tegund[spurn].equals("mynd")){
                            String svar = questionAction[fsvar];
                            if(verkefnaskilspurningar != null && isPartof(verkefnaskilspurningar,Integer.parseInt(spurningarID))){
                                Verkefnaskilspurningar.update(verkefnaskil_id, Integer.parseInt(spurningarID),svar);
                            }
                            else{
                                Verkefnaskilspurningar.create(verkefnaskil_id, Integer.parseInt(spurningarID),svar);
                            }
                            fsvar++;
                        }

                        if(tegund[spurn].equals("krossar")){
                            String[] krossaSvar  = null;
                            String getKross = "krossarSvar"+spurningarID;   //Have to have the id as well so the questions don't blend together.
                            if(body.asFormUrlEncoded().get(getKross)!= null){
                                krossaSvar = body.asFormUrlEncoded().get(getKross);
                                krossar.add(krossaSvar[0]);
                            }
                            if(verkefnaskilspurningar != null && isPartof(verkefnaskilspurningar, Integer.parseInt(spurningarID))){
                                Verkefnaskilspurningar.update(verkefnaskil_id, Integer.parseInt(spurningarID),krossaSvar[0]);
                            }
                            else if(krossaSvar != null){
                                    Verkefnaskilspurningar.create(verkefnaskil_id,Integer.parseInt(spurningarID),krossaSvar[0]);

                            }
                        }
                        if(tegund[spurn].equals("fjolval")){
                            //If the student has already answered fjolvalspurning we have to delete his old answers and put in new once because if he answered that four answers were
                            //correct and then changed it to one we don't want to have 3 lines in the table with nothing in them.
                            if(verkefnaskilspurningar != null && isPartof(verkefnaskilspurningar, Integer.parseInt(spurningarID))){
                                List<Verkefnaskilspurningar> verkefnaskilsp = new ArrayList<Verkefnaskilspurningar>();
                                for(Verkefnaskilspurningar v : verkefnaskilspurningar){
                                    if(v.getSpurning_id() == Integer.parseInt(spurningarID)){
                                        verkefnaskilsp.add(v);
                                    }
                                }
                                for(Verkefnaskilspurningar v : verkefnaskilsp){
                                    Verkefnaskilspurningar.delete(v.getVerkefnaskilspurningar_id());
                                }
                            }
                            //Add the answers for fjolvalsspurning (either after having deleted the old ones or putting them in for the first time)
                            String[] fjolvalSvar = body.asFormUrlEncoded().get("fjolvalSvar");
                            for(int j = 0; j < fjolvalSvar.length; j++){
                                Verkefnaskilspurningar.create(verkefnaskil_id, Integer.parseInt(spurningarID),fjolvalSvar[j]);
                            }
                        }
                    }
                }

                //If the assignment only contains krossaspurningar then we calculate the grade automatic.
                boolean  baraKrossar = false;
                if(postAction != null){
                    baraKrossar = baraKrossar(tegund, postAction);
                }
                Double grade = 0.0;
                if(baraKrossar== true){
                    grade = calculateGradeKrossar(postAction,krossar, verkefni_id); //calculate the grade
                    verkefninemenda.updateGrade(verkefni_id, notandId, grade); //update the grade

                }
            }
        }

        return redirect(routes.StudentController.studentOneProject(verkefni_id));
    }
    //Checks if an assignment is just krossar .
    //returns true if all the questions in spurningar_id are of kind "krossar" (singleChoice questions)
    public static boolean baraKrossar(String[] tegund, String[] spurningar_id){
        for(int i = 0; i< spurningar_id.length; i++){
            if(!tegund[i].equals("krossar")){
                return false;
            }
        }
        return true;
    }
    //If we have only krossar then we calculate the grade.
    //calculates a grade from questions answered if they are all of the kind "krossar" (singleChoice)
    public static Double calculateGradeKrossar(String[] spurningar, List<String> svor, int verkefni_id){
        List<Verkefnaspurningar> vsp = Verkefnaspurningar.getByVerkefniID(verkefni_id);
        Double vaegi = 0.0;
        //Get the overall weight of the questions
        for(Verkefnaspurningar v : vsp){
            vaegi += v.vaegi;
        }

        Double einkunn = 0.0;
        List<Integer> spurningID = new ArrayList<Integer>();
        for(int i = 0; i< spurningar.length; i++){ //Get the ids for all the questions
            spurningID.add(Integer.parseInt(spurningar[i]));
        }
        //SpurningID, réttSvarID
        List<MultipleChoice> spurningarogSvor = Svor.getCorrectAnswers(spurningID); //Get the correct answers for all the questions
        for(MultipleChoice m: spurningarogSvor){
            for(Verkefnaspurningar verk : vsp){
                if(verk.spurningar_id == m.getSpurningID()){ //Set the weight of the questions
                    m.setVaegi(verk.vaegi);
                }
            }
        }
        //Go through all the questions and see if the student's answer is the correct answer, if it is then we add to the overall grade, otherwise we don't
        for(int i = 0; i< svor.size(); i++){
            if(spurningarogSvor.get(i).getSpurningID()==Integer.parseInt(spurningar[i]) && spurningarogSvor.get(i).getRettSvarID()==Integer.parseInt(svor.get(i))){
                einkunn += (spurningarogSvor.get(i).getVaegi()*1);
            }
        }
        double temp = einkunn/(vaegi/10);
        int r = (int)(temp * 100);
        double returnGrade = r / 100.0;

        return (returnGrade);
    }

    public static Result courses(int afangi_id){
        if(isTeacher(session().get("notandiId"))) {
            return redirect(routes.TeacherController.teacherDashboard());
        }
        String userId = session().get("notandiId");
        int intNotandi = Integer.parseInt(userId);
        List<Announcements> tilkynningar = new ArrayList<Announcements>();
        List<Announcements> top5Tilkynningar = new ArrayList<Announcements>();
        List<Students> students = new ArrayList<Students>();
        List<Project> projects = new ArrayList<Project>();
        List<verkefninemenda> verkefniNemenda = verkefninemenda.findAllByUserId(userId);
        List<Verkefni> verkefni = new ArrayList<Verkefni>();
        List<Project> tempProjects = new ArrayList<Project>();
        List<AverageProjects> averageAndStuff = new ArrayList<AverageProjects>();
        List<Baekur> baekur = new ArrayList<Baekur>();

        for(verkefninemenda v : verkefniNemenda){
            Verkefni verk = Verkefni.findProjectByVerkefniID(v.verkefni_id);
            verkefni.add(verk);
        }

        for(vNemandiAfangarOnn afangi : afangar){
            //Tilkynningar
            List<Tilkynning> tilkynning = Tilkynning.getAfangiTilkynningarSorted(Integer.toString(afangi.getAfangi_id()));
            List<Announcements> tempTilkynning = new ArrayList<Announcements>();
            //Get all announcements
            for(Tilkynning t : tilkynning){
                if(Integer.parseInt(t.getAfangi_id()) == afangi.getAfangi_id()){
                    tempTilkynning.add(new Announcements(t.getTexti(), simpleDateFormat.format(t.getDagur_stofnad()), t.getFyrirsogn(), t.getAfangi_id()));
                }
            }
            //Get the 5 newest announcements
            List<Announcements> temp5Tilkynning = new ArrayList<Announcements>();
            if(tempTilkynning != null && tempTilkynning.size() >=4){
                for(int i = 0; i < 5 ; i++){
                    temp5Tilkynning.add(new Announcements(tempTilkynning.get(i).getTexti(), tempTilkynning.get(i).getDagur_stofnad(),
                            tempTilkynning.get(i).getFyrirsogn(),tempTilkynning.get(i).getAfangi_id()));
                }
            }
            if(tempTilkynning != null && tempTilkynning.size() <4){
                for(int i = 0; i < tempTilkynning.size(); i++){
                    temp5Tilkynning.add(new Announcements(tempTilkynning.get(i).getTexti(), tempTilkynning.get(i).getDagur_stofnad(),
                            tempTilkynning.get(i).getFyrirsogn(), tempTilkynning.get(i).getAfangi_id()));
                }
            }
            if(tempTilkynning == null){
                temp5Tilkynning = null;
            }
            if(tempTilkynning != null){
                tilkynningar.add(new Announcements(afangi.getAfangi_id(), tempTilkynning));
            }
            if(temp5Tilkynning != null){
                top5Tilkynningar.add(new Announcements(afangi.getAfangi_id(), temp5Tilkynning));
            }

            //Nemendalisti
            List<Students> tempStudent = new ArrayList<Students>();
            //Get all the students for all the courses the student is taking
            for(vNemandiAfangarOnn g : afangar){
                List<vNemandiAfangarOnn> tempStudents = null;
                if(g.getAfangi_id() == afangi.getAfangi_id()){
                    tempStudents = vNemandiAfangarOnn.findStudentsByGroup(g.getHopur_id());
                }
                if(tempStudents != null){
                    for(vNemandiAfangarOnn v: tempStudents){
                        tempStudent.add(new Students(Integer.toString(v.getNotandi_id()),v.getNafn(),g.getHopur(),v.getKennitala()));
                    }
                    //Add the course id and a list of student that are in that  group
                    students.add(new Students(afangi.getAfangi_id(),tempStudent));
                }
            }
            //Verkefni og próf
            Date today = new Date();
            List<Project> openProject = new ArrayList<Project>();
            List<Project> closedProject = new ArrayList<Project>();
           List<Verkefni> verkefniID = new ArrayList<Verkefni>();
            //Get all the project for a student, no matter if it is a test, project, open or closed
            for(verkefninemenda v: verkefniNemenda){ //verkefninemenda er vNemenda...
                Verkefni verk = Verkefni.findProjectByVerkefniID(v.verkefni_id);
                    verkefnihops vhops = verkefnihops.findProjectByVerkefniIDHopurID(v.verkefni_id, afangi.getHopur_id());
                    if(v!=null && verk != null && vhops!= null){
                        if(afangi.getAfangi_id() == Integer.parseInt(verk.getAfangi_id()) && vhops.getVerkefni_id() == v.getVerkefni_id()&& v.getVerkefni_id() == verk.getVerkefni_id() && v.getNemandi_id().equals(userId)){
                            verkefniID.add(verk);
                            int returned = verkefninemenda.hasStudentTurnedInProject(v.verkefni_id, intNotandi);
                            tempProjects.add(new Project(verk.getHeiti(),afangi.getAfangi_id(),vhops.getUpphafsdagsetning(),vhops.getLokadagsetning(),
                                    verk.getVaegi(), v.getEinkunn(), v.getVerkefni_id(), verk.getTegund()));
                    }
                }
            }
            Double average=0.0;
            int count = 0;
            Double weightedAverage=0.0;
            Double overAllWeight =0.0;

            tempProjects = CommonController.sortProjectsByDate(tempProjects);
            for(Project proj : tempProjects){
                int returned = verkefninemenda.hasStudentTurnedInProject(proj.getVerkefni_id(), intNotandi);
                if(afangi.getAfangi_id() == proj.getAfangi_id()){  //always true
                    String beginDate = simpleDateFormat.format((proj.getBeginDateFormat()));
                    String endDate = simpleDateFormat.format(proj.getHandinDateFormat());
                    //All closed projects
                    if(today.before(proj.getHandinDateFormat()) && today.after(proj.getBeginDateFormat())){
                        if(returned ==1){
                            closedProject.add(new Project(proj.getName(),proj.getGrade(),proj.getWeight(),proj.getAfangi_id(),true,beginDate,endDate,proj.getType(),proj.getVerkefni_id()));
                        }
                        else{
                            closedProject.add(new Project(proj.getName(),proj.getGrade(),proj.getWeight(),proj.getAfangi_id(),false,beginDate,endDate,proj.getType(),proj.getVerkefni_id()));

                        }
                    }
                    //All open projects
                    else if(today.after(proj.getBeginDateFormat())){

                        if(returned == 1){
                            openProject.add(new Project(proj.getName(), proj.getGrade(),proj.getWeight(), proj.getAfangi_id(), true,beginDate,endDate,proj.getType(),proj.getVerkefni_id()));
                        }
                        else{
                            openProject.add(new Project(proj.getName(),proj.getGrade(),proj.getWeight(),proj.getAfangi_id(),false,beginDate,endDate,proj.getType(),proj.getVerkefni_id()));
                        }
                    }
                    //einkunnir
                    //Calculate average and other statistics for all of the students projects for that particular course.
                        if(proj.getGrade() < 20){
                            average += proj.getGrade();
                            weightedAverage += (proj.getGrade()*proj.getWeight());
                            overAllWeight += proj.getWeight();
                            count++;
                        }
                }
            }
            if(openProject.size()== 0){
                openProject = null;
            }
            if(closedProject.size() == 0){
                closedProject = null;
            }

            if(openProject != null && closedProject != null){
                projects.add(new Project(afangi.getAfangi_id(),openProject,closedProject));
            }
            if(openProject == null && closedProject != null){
                projects.add(new Project(afangi.getAfangi_id(),null,closedProject));
            }
            if(openProject != null && closedProject == null){
                projects.add(new Project(afangi.getAfangi_id(),openProject,null));
            }
            else{
                projects.add(new Project(afangi.getAfangi_id(),null,null));
            }


            if(count != 0){
                average = average/count;
                int r = (int)(average * 100);
                average = r/100.0;
            }
            Double earnedGrade = weightedAverage/100;
            int a = (int) (earnedGrade*100);
            earnedGrade = a/100.0;
            if(overAllWeight != 0){
                weightedAverage = weightedAverage/overAllWeight;
                int r = (int) (weightedAverage*100);
                weightedAverage = r/100.0;
            }
            averageAndStuff.add(new AverageProjects(afangi.getAfangi_id(),average,earnedGrade,weightedAverage, overAllWeight, (overAllWeight/10)));


            //Baekur
            //All books for that particular course.
            List<Baekur> bokHofundur = new ArrayList<Baekur>();
            for(vAfangarBaekur afangaBaekur : courseBooks){
                if(afangaBaekur.getAfangi_id() == afangi.getAfangi_id()){
                    if(afangaBaekur.getHeiti() == null){
                        bokHofundur.add(new Baekur(null,afangaBaekur.getHofundur()));
                    }
                    if(afangaBaekur.getHofundur() == null){
                        bokHofundur.add(new Baekur(afangaBaekur.getHeiti(),null));
                    }
                    if(afangaBaekur.getHeiti() != null && afangaBaekur.getHofundur() != null){
                        bokHofundur.add(new Baekur(afangaBaekur.getHeiti(),afangaBaekur.getHofundur(), afangaBaekur.getUtgafa(),afangaBaekur.getUtgefandi()));
                    }
                }
            }
            if(bokHofundur != null){
                bokHofundur = CommonController.sortBooksByName(bokHofundur);
                baekur.add(new Baekur(afangi.getAfangi_id(),bokHofundur));
            }
            else{
                baekur.add(new Baekur(afangi.getAfangi_id(),null));
            }

        }


        return ok(courses.render(afangar, tilkynningar, top5Tilkynningar, students,projects, tempProjects, averageAndStuff, afangi_id, baekur));
    }


    public static List<Graph> calculateAunninForAllStudents(int xLimit, String studentID, List<Verkefni> verkefni_id, int afangi_id, List<Students> students){
        List<Graph> graphData = new ArrayList<Graph>();
        for(double i = 0; i <= xLimit ; i+=0.5){
            graphData.add(new Graph(i,0,false));
        }
        for(Students student : students){
            //earned grade = weightAverage/100;
            double weightedAverage = 0.0;
            double overAllWeight = 0.0;
            double earnedGrade= 0.0;
            for(Verkefni verk: verkefni_id){
                double grade = verkefninemenda.getGrade(verk.getVerkefniId(), student.nemandi_id);
                if(grade < 20){
                    weightedAverage += (grade* verk.getVaegi());
                    overAllWeight += verk.getVaegi();
                }
            }
            if(weightedAverage != 0 && overAllWeight != 0){
                earnedGrade = (weightedAverage/overAllWeight)/10;
            }
            if(earnedGrade != 0){
                for(double i = 0; i < (xLimit-0.5) ; i+= 0.5){
                    if(isBetween(earnedGrade,i, (i+0.5))){
                        if(student.getNemandi_id().equals(studentID)){
                            graphData.get((int) (i*2)).setYou(true);
                        }
                        if(isCloser(earnedGrade,i,(i+0.5)) == i){
                            graphData.get((int)(i*2)).incrementY();
                        }
                        else{
                            graphData.get((int)((i+0.5)*2)).incrementY();
                        }
                    }
                }
            }
        }
        return graphData;
    }

    //used to check which pillar the grade is closer to
    public static double isCloser(double x, double lower, double upper){
        double middle = (upper+lower)/2;
        if(x < middle){
            return lower;
        }
        else{
            return upper;
        }
    }

    //All announcment for students (announcements from all of his courses and for the entire school).
    public static Result allStudentAnnouncements() {
        if(isTeacher(session().get("notandiId"))) {
            return redirect(routes.TeacherController.teacherDashboard());
        }
        List<Tilkynning> tilkynningList = Tilkynning.getAllStudentAnnouncements(afangar);
        List<Announcements> announcements = Announcements.createAnnouncementList(tilkynningList);
        return ok(AllStudentAnnouncements.render(announcements));
    }

    public static Result studentTimeTable(){
        List<List<Stundatoflur_NK>> stundatafla = Stundatoflur_NK.getStudentStundatafla(afangar);  //List that has a seperate list for the course schedule each day
        List<List<Heimavinna>> heimavinna = Heimavinna.getStudentHomeworkWeek(afangar);  //List that has a seperate list for the homework each day
        List<TimetableHomework> all = TimetableHomework.makeTimetableHomework(stundatafla, heimavinna);

        List<TimetableHomework> oneRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> twoRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> threeRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> fourRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> fiveRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> sixRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> sevenRow=new ArrayList<TimetableHomework>();
        List<TimetableHomework> eightRow=new ArrayList<TimetableHomework>();
        for(int i=0;i<40;i= i+8){
            if(all.get(i).getId()==(i+1)){
                oneRow.add(all.get(i));
            }
        }
        for(int i=1;i<40;i= i+8){
            if(all.get(i).getId()==(i+1)){
                twoRow.add(all.get(i));
            }
        }
        for(int i=2;i<40;i= i+8){
            if(all.get(i).getId()==(i+1)){
                threeRow.add(all.get(i));
            }
        }
        for(int i=3;i<40;i= i+8){
            if(all.get(i).getId()==(i+1)){
                fourRow.add(all.get(i));
            }
        }
        for(int i=4;i<40;i= i+8){
            if(all.get(i).getId()==(i+1)){
                fiveRow.add(all.get(i));
            }
        }
        for(int i=5;i<40;i= i+8){
            if(all.get(i).getId()==(i+1)){
                sixRow.add(all.get(i));
            }
        }
        for(int i=6;i<40;i= i+8){
            if(all.get(i).getId()==(i+1)){
                sevenRow.add(all.get(i));
            }
        }
        for(int i=7;i<40;i= i+8){
            if(all.get(i).getId()==(i+1)){
                eightRow.add(all.get(i));
            }
        }

        return ok(StudentTimeTable.render(oneRow, twoRow, threeRow, fourRow, fiveRow, sixRow, sevenRow, eightRow));
    }
}
